package org.haifi.game.mina;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.haifi.game.reflection.GameReflect;

import com.google.protobuf.MessageLite;

/**
 * 编码器
 * 
 * 头两个字节是protobuf对象的长度
 * 
 * 两个字节的指令id
 * 
 * 一个字节的loop,用来进行验证
 * 
 * 然后是protobuf对象数据
 * 
 * @author joycube2
 * 
 */
public class GameEncoderFilter extends ProtocolEncoderAdapter {

	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		// TODO Auto-generated method stub
		// GameCoderObject commandCoderObject = (GameCoderObject) message;
		MessageLite.Builder messageLite = (MessageLite.Builder) message;
		byte[] protoData = messageLite.build().toByteArray();
		IoBuffer buffer = IoBuffer.allocate(protoData.length + 5);
		buffer.putShort((short) protoData.length);
		buffer.putShort(GameReflect.getReturnCmdId(message.getClass()));
		buffer.put((byte) 0);// TODO:这里有必要发送loop数据吗
		buffer.put(protoData);
		buffer.flip();
		out.write(buffer);
	}

}
